<script setup lang="ts">
import { getRolesWithUserPermissions, allocateUserRoles, type TUserRole } from '@/api/users'
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  userId: -1,
  roleIdList: [] as number[]
})
const allRoles = ref([] as TUserRole[])
// 封装显示方法
const initAndShow = async (userId: number) => {
  dialogFormVisible.value = true
  const { data } = await getRolesWithUserPermissions(userId)
  if (data.code === '000000') {
    allRoles.value = data.data
    form.userId = userId
    // 过滤出拥有的的权限id
    form.roleIdList = []
    form.roleIdList = data.data.filter((role) => role.hasPermission).map((r) => r.id)
  } else {
    ElMessage.error('获取用户角色失败！')
    throw new Error('获取用户角色失败' + data.mesg)
  }
}

// 暴露给父组件使用
defineExpose({ initAndShow })

const onSubmit = async () => {
  dialogFormVisible.value = false
  const { data } = await allocateUserRoles(form.userId, form.roleIdList)
  if (data.code === '000000') {
    ElMessage.success('用户角色权限保存成功！')
  } else {
    ElMessage.error('用户角色权限保存失败！')
    throw new Error('用户角色权限保存失败' + data.mesg)
  }
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="分配角色">
    <el-form :model="form">
      <el-form-item label="" :label-width="formLabelWidth">
        <el-select v-model="form.roleIdList" placeholder="请选择角色" multiple>
          <el-option v-for="role in allRoles" :key="role.id" :label="role.name" :value="role.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
